<template>
  <div v-if="is_info" class="text-ellipsis" :title="value_str">{{value_str}}</div>
  <div v-else class="form_item-area">
    <input type="hidden" :name="name" :value="value">
    <el-cascader v-model="this_value" :size="size" :options="options" :props="props" @change="update_value" style="width: 100%;"></el-cascader>
  </div>
</template>

<script>
import s94Mjs from "s94-js";
import {ajax} from "@/js/api_tool.js";

export default {
  _title_: '选择区域',
  _can_form_param_: true,
  name: "area_4l",
  props: ['name', 'value', 'config', 'is_info', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    let app = this;
    return {
      need_display: true,
      this_value: this.value_arr(),
      options: [],
      props: {
        lazy: true,
        lazyLoad(node, resolve){
          let id = node.value || 0;
          app.get_children(id, node.level, function (list){
            resolve(list);
          });
        }
      }
    }
  },
  methods: {
    value_arr(){
      let val = s94Mjs.trim(s94Mjs.to_string(this.value), ',');
      return val ? val.split(',') : [];
    },
    update_value(arr){
      this.need_display = false;
      setTimeout(()=>{this.need_display = true;},5);
      this.$emit('update:value', arr.join(','));
      this.$emit('change', arr.join(','));
    },
    get_children(id, level, callback){
      let app = this, in_list = false, value_level = this.value_arr()[level];
      ajax({url:'/home/api/area?parent_id='+id, cache:true}, function (res){
        let list = res.data.list.map((row)=>{
          let val = s94Mjs.to_string(row.id);
          in_list = (in_list || value_level==val);
          return {value: val, label: row.name, leaf: level>=3}
        })
        callback(list);
        return false;
      })
    },
  },
  watch: {
    value(){
      if (!this.need_display) return;
      this.this_value = this.value_arr();
    }
  },
  computed: {
    value_str(){
      let value_arr = this.value_arr();
      if (value_arr.length == 0) return '';
      let name_arr = [];
      ajax({url:'/home/api/area?ids='+value_arr.join(','), cache:true, async:false}, function (res){
        res.data.list.forEach(function (row){
          let i = value_arr.indexOf(row.id+'');
          name_arr[i] = row.name;
        })
        return false;
      })
      return name_arr.join(' ');
    }
  },
  mounted() {

  }
}
</script>

<style scoped>

</style>